from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc, asc, and_, or_, func
from typing import Optional
from datetime import date, datetime
from database import get_db
from models import Contest, Work, User, WorkLike, WorkFavorite, WorkComment, ContestParticipant, WorkShare
from schemas import (
    ResponseModel, 
    ContestResponse, 
    ContestListResponse, 
    ContestStatus,
    ContestWorkResponse,
    ContestWorkListResponse,
    WorkLikeResponse,
    WorkFavoriteResponse,
    CommentCreate,
    CommentResponse,
    CommentListResponse,
    ContestJoinResponse,
    ContestParticipantResponse,
    WorkSubmitRequest,
    WorkSubmitResponse,
    WorkShareRequest,
    WorkShareResponse
)
from auth import get_current_active_user

router = APIRouter(prefix="/api/contests", tags=["竞赛信息"])

def update_contest_status(db: Session):
    """
    更新竞赛状态
    根据当前日期自动更新竞赛状态
    
    Args:
        db: 数据库会话
    """
    today = date.today()
    
    # 更新即将开始的竞赛为进行中
    db.query(Contest).filter(
        Contest.start_date <= today,
        Contest.end_date >= today,
        Contest.status == ContestStatus.UPCOMING
    ).update({Contest.status: ContestStatus.ONGOING})
    
    # 更新已结束的竞赛
    db.query(Contest).filter(
        Contest.end_date < today,
        or_(Contest.status == ContestStatus.UPCOMING, Contest.status == ContestStatus.ONGOING)
    ).update({Contest.status: ContestStatus.ENDED})
    
    db.commit()

@router.get("", response_model=ResponseModel)
async def get_contests(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    status: Optional[ContestStatus] = Query(None, description="竞赛状态过滤"),
    category: Optional[str] = Query(None, description="竞赛分类过滤"),
    sort: str = Query("latest", description="排序方式: latest/start_date/end_date/participants"),
    db: Session = Depends(get_db)
):
    """
    获取竞赛列表
    
    Args:
        page: 页码
        limit: 每页数量
        status: 竞赛状态过滤
        category: 竞赛分类过滤
        sort: 排序方式
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含竞赛列表的响应
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 构建查询
    query = db.query(Contest)
    
    # 状态过滤
    if status:
        query = query.filter(Contest.status == status)
    
    # 分类过滤
    if category:
        query = query.filter(Contest.category == category)
    
    # 排序
    if sort == "start_date":
        query = query.order_by(asc(Contest.start_date))
    elif sort == "end_date":
        query = query.order_by(asc(Contest.end_date))
    elif sort == "participants":
        query = query.order_by(desc(Contest.participant_count))
    else:  # latest
        query = query.order_by(desc(Contest.created_at))
    
    # 获取总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * limit
    contests = query.offset(offset).limit(limit).all()
    
    # 转换为响应格式
    contests_data = []
    for contest in contests:
        contests_data.append({
            "id": contest.id,
            "title": contest.title,
            "description": contest.description,
            "startDate": contest.start_date.isoformat(),
            "endDate": contest.end_date.isoformat(),
            "status": contest.status,
            "prize": contest.prize,
            "organizer": contest.organizer,
            "category": contest.category,
            "createdAt": contest.created_at.isoformat()
        })
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "total": total,
            "page": page,
            "limit": limit,
            "contests": contests_data
        }
    )

@router.get("/{contest_id}", response_model=ResponseModel)
async def get_contest_detail(
    contest_id: int,
    db: Session = Depends(get_db)
):
    """
    获取竞赛详情
    
    Args:
        contest_id: 竞赛ID
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含竞赛详情的响应
    
    Raises:
        HTTPException: 如果竞赛不存在
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 查询竞赛
    contest = db.query(Contest).filter(Contest.id == contest_id).first()
    
    if not contest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="竞赛不存在"
        )
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "id": contest.id,
            "title": contest.title,
            "description": contest.description,
            "rules": contest.rules,
            "startDate": contest.start_date.isoformat(),
            "endDate": contest.end_date.isoformat(),
            "status": contest.status,
            "prize": contest.prize,
            "organizer": contest.organizer,
            "category": contest.category,
            "participantCount": contest.participant_count,
            "createdAt": contest.created_at.isoformat()
        }
    )

@router.get("/featured/upcoming", response_model=ResponseModel)
async def get_featured_upcoming_contests(
    limit: int = Query(5, ge=1, le=20, description="返回数量"),
    db: Session = Depends(get_db)
):
    """
    获取精选即将开始的竞赛
    
    Args:
        limit: 返回数量
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含精选竞赛的响应
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 查询即将开始的竞赛，按开始时间排序
    contests = db.query(Contest).filter(
        Contest.status == ContestStatus.UPCOMING
    ).order_by(asc(Contest.start_date)).limit(limit).all()
    
    contests_data = []
    for contest in contests:
        contests_data.append({
            "id": contest.id,
            "title": contest.title,
            "description": contest.description,
            "startDate": contest.start_date.isoformat(),
            "endDate": contest.end_date.isoformat(),
            "status": contest.status,
            "prize": contest.prize,
            "organizer": contest.organizer,
            "category": contest.category,
            "participantCount": contest.participant_count
        })
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "contests": contests_data
        }
    )

@router.get("/featured/hot", response_model=ResponseModel)
async def get_hot_contests(
    limit: int = Query(5, ge=1, le=20, description="返回数量"),
    db: Session = Depends(get_db)
):
    """
    获取热门竞赛（按参与人数排序）
    
    Args:
        limit: 返回数量
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含热门竞赛的响应
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 查询进行中的竞赛，按参与人数排序
    contests = db.query(Contest).filter(
        Contest.status == ContestStatus.ONGOING
    ).order_by(desc(Contest.participant_count)).limit(limit).all()
    
    contests_data = []
    for contest in contests:
        contests_data.append({
            "id": contest.id,
            "title": contest.title,
            "description": contest.description,
            "startDate": contest.start_date.isoformat(),
            "endDate": contest.end_date.isoformat(),
            "status": contest.status,
            "prize": contest.prize,
            "organizer": contest.organizer,
            "category": contest.category,
            "participantCount": contest.participant_count
        })
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "contests": contests_data
        }
    )

@router.get("/stats/summary", response_model=ResponseModel)
async def get_contest_stats(
    db: Session = Depends(get_db)
):
    """
    获取竞赛统计信息
    
    Args:
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含竞赛统计信息的响应
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 统计各状态竞赛数量
    total_contests = db.query(Contest).count()
    upcoming_count = db.query(Contest).filter(Contest.status == ContestStatus.UPCOMING).count()
    ongoing_count = db.query(Contest).filter(Contest.status == ContestStatus.ONGOING).count()
    ended_count = db.query(Contest).filter(Contest.status == ContestStatus.ENDED).count()
    
    # 统计各分类竞赛数量
    category_stats = {}
    categories = ["video", "image", "music", "text"]
    for category in categories:
        count = db.query(Contest).filter(Contest.category == category).count()
        category_stats[category] = count
    
    # 统计总参与人数
    total_participants = db.query(Contest).with_entities(
        db.func.sum(Contest.participant_count)
    ).scalar() or 0
    
    return ResponseModel(
            code=200,
            message="success",
            data={
                "totalContests": total_contests,
                "statusStats": {
                    "upcoming": upcoming_count,
                    "ongoing": ongoing_count,
                    "ended": ended_count
                },
                "categoryStats": category_stats,
                "totalParticipants": total_participants
            }
        )

@router.get("/{contest_id}/works", response_model=ResponseModel)
async def get_contest_works(
    contest_id: int,
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    sort: str = Query("latest", description="排序方式: latest/popular/views/likes"),
    current_user: Optional[User] = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取竞赛参赛作品列表
    
    Args:
        contest_id: 竞赛ID
        page: 页码
        limit: 每页数量
        sort: 排序方式
        current_user: 当前登录用户（可选）
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含竞赛作品列表的响应
    
    Raises:
        HTTPException: 如果竞赛不存在
    """
    # 检查竞赛是否存在
    contest = db.query(Contest).filter(Contest.id == contest_id).first()
    if not contest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="竞赛不存在"
        )
    
    # 构建查询
    query = db.query(Work).filter(Work.contest_id == contest_id)
    
    # 排序
    if sort == "popular":
        query = query.order_by(desc(Work.views))
    elif sort == "likes":
        query = query.order_by(desc(Work.likes))
    elif sort == "views":
        query = query.order_by(desc(Work.views))
    else:  # latest
        query = query.order_by(desc(Work.created_at))
    
    # 获取总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * limit
    works = query.offset(offset).limit(limit).all()
    
    # 转换为响应格式
    works_data = []
    for work in works:
        # 获取用户信息
        user_info = {
            "id": work.user.id,
            "username": work.user.username,
            "nickname": work.user.nickname,
            "avatar": work.user.avatar
        }
        
        # 检查当前用户是否已点赞/收藏
        is_liked = False
        is_favorited = False
        if current_user:
            is_liked = db.query(WorkLike).filter(
                WorkLike.user_id == current_user.id,
                WorkLike.work_id == work.id
            ).first() is not None
            
            is_favorited = db.query(WorkFavorite).filter(
                WorkFavorite.user_id == current_user.id,
                WorkFavorite.work_id == work.id
            ).first() is not None
        
        works_data.append({
            "id": work.id,
            "title": work.title,
            "description": work.description,
            "category": work.category,
            "tags": work.tags or [],
            "file_url": work.file_url,
            "thumbnail": work.thumbnail,
            "views": work.views,
            "likes": work.likes,
            "comments": work.comments,
            "user_id": work.user_id,
            "contest_id": work.contest_id,
            "created_at": work.created_at.isoformat(),
            "updated_at": work.updated_at.isoformat() if work.updated_at else None,
            "user": user_info,
            "is_liked": is_liked,
            "is_favorited": is_favorited
        })
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "total": total,
            "page": page,
            "limit": limit,
            "works": works_data
        }
    )

@router.post("/{contest_id}/works/{work_id}/like", response_model=ResponseModel)
async def toggle_work_like(
    contest_id: int,
    work_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    切换作品点赞状态
    
    Args:
        contest_id: 竞赛ID
        work_id: 作品ID
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含点赞状态的响应
    
    Raises:
        HTTPException: 如果作品不存在或不属于该竞赛
    """
    # 检查作品是否存在且属于该竞赛
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.contest_id == contest_id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或不属于该竞赛"
        )
    
    # 检查是否已点赞
    existing_like = db.query(WorkLike).filter(
        WorkLike.user_id == current_user.id,
        WorkLike.work_id == work_id
    ).first()
    
    if existing_like:
        # 取消点赞
        db.delete(existing_like)
        work.likes = max(0, work.likes - 1)
        is_liked = False
    else:
        # 添加点赞
        new_like = WorkLike(user_id=current_user.id, work_id=work_id)
        db.add(new_like)
        work.likes += 1
        is_liked = True
    
    db.commit()
    
    return ResponseModel(
        code=200,
        message="操作成功",
        data={
            "is_liked": is_liked,
            "likes_count": work.likes
        }
    )

@router.post("/{contest_id}/works/{work_id}/favorite", response_model=ResponseModel)
async def toggle_work_favorite(
    contest_id: int,
    work_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    切换作品收藏状态
    
    Args:
        contest_id: 竞赛ID
        work_id: 作品ID
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含收藏状态的响应
    
    Raises:
        HTTPException: 如果作品不存在或不属于该竞赛
    """
    # 检查作品是否存在且属于该竞赛
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.contest_id == contest_id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或不属于该竞赛"
        )
    
    # 检查是否已收藏
    existing_favorite = db.query(WorkFavorite).filter(
        WorkFavorite.user_id == current_user.id,
        WorkFavorite.work_id == work_id
    ).first()
    
    if existing_favorite:
        # 取消收藏
        db.delete(existing_favorite)
        is_favorited = False
    else:
        # 添加收藏
        new_favorite = WorkFavorite(user_id=current_user.id, work_id=work_id)
        db.add(new_favorite)
        is_favorited = True
    
    db.commit()
    
    # 获取收藏总数
    favorites_count = db.query(WorkFavorite).filter(
        WorkFavorite.work_id == work_id
    ).count()
    
    return ResponseModel(
        code=200,
        message="操作成功",
        data={
            "is_favorited": is_favorited,
            "favorites_count": favorites_count
        }
    )

@router.get("/{contest_id}/works/{work_id}/comments", response_model=ResponseModel)
async def get_work_comments(
    contest_id: int,
    work_id: int,
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db)
):
    """
    获取作品评论列表
    
    Args:
        contest_id: 竞赛ID
        work_id: 作品ID
        page: 页码
        limit: 每页数量
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含评论列表的响应
    
    Raises:
        HTTPException: 如果作品不存在或不属于该竞赛
    """
    # 检查作品是否存在且属于该竞赛
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.contest_id == contest_id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或不属于该竞赛"
        )
    
    # 查询顶级评论（非回复）
    query = db.query(WorkComment).filter(
        WorkComment.work_id == work_id,
        WorkComment.parent_id.is_(None)
    ).order_by(desc(WorkComment.created_at))
    
    # 获取总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * limit
    comments = query.offset(offset).limit(limit).all()
    
    # 转换为响应格式
    comments_data = []
    for comment in comments:
        # 获取用户信息
        user_info = {
            "id": comment.user.id,
            "username": comment.user.username,
            "nickname": comment.user.nickname,
            "avatar": comment.user.avatar
        }
        
        # 获取回复
        replies = db.query(WorkComment).filter(
            WorkComment.parent_id == comment.id
        ).order_by(asc(WorkComment.created_at)).all()
        
        replies_data = []
        for reply in replies:
            reply_user_info = {
                "id": reply.user.id,
                "username": reply.user.username,
                "nickname": reply.user.nickname,
                "avatar": reply.user.avatar
            }
            
            replies_data.append({
                "id": reply.id,
                "content": reply.content,
                "user_id": reply.user_id,
                "work_id": reply.work_id,
                "parent_id": reply.parent_id,
                "created_at": reply.created_at.isoformat(),
                "updated_at": reply.updated_at.isoformat() if reply.updated_at else None,
                "user": reply_user_info,
                "replies": []
            })
        
        comments_data.append({
            "id": comment.id,
            "content": comment.content,
            "user_id": comment.user_id,
            "work_id": comment.work_id,
            "parent_id": comment.parent_id,
            "created_at": comment.created_at.isoformat(),
            "updated_at": comment.updated_at.isoformat() if comment.updated_at else None,
            "user": user_info,
            "replies": replies_data
        })
    
    return ResponseModel(
        code=200,
        message="success",
        data={
            "total": total,
            "page": page,
            "limit": limit,
            "comments": comments_data
        }
    )

@router.post("/{contest_id}/works/{work_id}/comments", response_model=ResponseModel)
async def create_work_comment(
    contest_id: int,
    work_id: int,
    comment_data: CommentCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    创建作品评论
    
    Args:
        contest_id: 竞赛ID
        work_id: 作品ID
        comment_data: 评论数据
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含评论信息的响应
    
    Raises:
        HTTPException: 如果作品不存在或不属于该竞赛
    """
    # 检查作品是否存在且属于该竞赛
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.contest_id == contest_id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或不属于该竞赛"
        )
    
    # 如果是回复，检查父评论是否存在
    if comment_data.parent_id:
        parent_comment = db.query(WorkComment).filter(
            WorkComment.id == comment_data.parent_id,
            WorkComment.work_id == work_id
        ).first()
        
        if not parent_comment:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="父评论不存在"
            )
    
    # 创建评论
    new_comment = WorkComment(
        content=comment_data.content,
        user_id=current_user.id,
        work_id=work_id,
        parent_id=comment_data.parent_id
    )
    
    db.add(new_comment)
    
    # 更新作品评论数
    work.comments += 1
    
    db.commit()
    db.refresh(new_comment)
    
    # 获取用户信息
    user_info = {
        "id": current_user.id,
        "username": current_user.username,
        "nickname": current_user.nickname,
        "avatar": current_user.avatar
    }
    
    return ResponseModel(
        code=200,
        message="评论发布成功",
        data={
            "id": new_comment.id,
            "content": new_comment.content,
            "user_id": new_comment.user_id,
            "work_id": new_comment.work_id,
            "parent_id": new_comment.parent_id,
            "created_at": new_comment.created_at.isoformat(),
            "updated_at": new_comment.updated_at.isoformat() if new_comment.updated_at else None,
            "user": user_info,
            "replies": []
        }
    )

@router.post("/{contest_id}/join", response_model=ResponseModel)
async def join_contest(
    contest_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    用户参与竞赛
    
    Args:
        contest_id: 竞赛ID
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含参与结果的响应
    
    Raises:
        HTTPException: 如果竞赛不存在或已结束
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 检查竞赛是否存在
    contest = db.query(Contest).filter(Contest.id == contest_id).first()
    
    if not contest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="竞赛不存在"
        )
    
    # 检查竞赛状态
    if contest.status == ContestStatus.ENDED:
        return ResponseModel(
            code=400,
            message="竞赛已结束，无法参与",
            data={
                "success": False,
                "message": "竞赛已结束，无法参与",
                "status": "contest_ended"
            }
        )
    
    # 检查用户是否已经参与
    existing_participant = db.query(ContestParticipant).filter(
        ContestParticipant.user_id == current_user.id,
        ContestParticipant.contest_id == contest_id
    ).first()
    
    if existing_participant:
        return ResponseModel(
            code=200,
            message="您已经参与了该竞赛",
            data={
                "success": True,
                "message": "您已经参与了该竞赛",
                "participant_id": existing_participant.id,
                "status": "already_joined"
            }
        )
    
    # 创建参与记录
    new_participant = ContestParticipant(
        user_id=current_user.id,
        contest_id=contest_id,
        status="joined"
    )
    
    db.add(new_participant)
    
    # 更新竞赛参与人数
    contest.participant_count += 1
    
    db.commit()
    db.refresh(new_participant)
    
    return ResponseModel(
        code=200,
        message="成功参与竞赛",
        data={
            "success": True,
            "message": "成功参与竞赛",
            "participant_id": new_participant.id,
            "status": "joined"
        }
    )

@router.post("/{contest_id}/submit", response_model=ResponseModel)
async def submit_work(
    contest_id: int,
    work_data: WorkSubmitRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    提交竞赛作品
    
    Args:
        contest_id: 竞赛ID
        work_data: 作品数据
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含提交结果的响应
    
    Raises:
        HTTPException: 如果竞赛不存在、已结束或用户未参与
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 检查竞赛是否存在
    contest = db.query(Contest).filter(Contest.id == contest_id).first()
    
    if not contest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="竞赛不存在"
        )
    
    # 检查竞赛状态
    if contest.status == ContestStatus.ENDED:
        return ResponseModel(
            code=400,
            message="竞赛已结束，无法提交作品",
            data={
                "success": False,
                "message": "竞赛已结束，无法提交作品"
            }
        )
    
    if contest.status == ContestStatus.UPCOMING:
        return ResponseModel(
            code=400,
            message="竞赛尚未开始，无法提交作品",
            data={
                "success": False,
                "message": "竞赛尚未开始，无法提交作品"
            }
        )
    
    # 检查用户是否已参与竞赛
    participant = db.query(ContestParticipant).filter(
        ContestParticipant.user_id == current_user.id,
        ContestParticipant.contest_id == contest_id
    ).first()
    
    if not participant:
        return ResponseModel(
            code=400,
            message="您尚未参与该竞赛，请先参与竞赛",
            data={
                "success": False,
                "message": "您尚未参与该竞赛，请先参与竞赛"
            }
        )
    
    # 检查用户是否已经提交过作品
    existing_work = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.contest_id == contest_id
    ).first()
    
    if existing_work:
        return ResponseModel(
            code=400,
            message="您已经提交过作品，每个竞赛只能提交一个作品",
            data={
                "success": False,
                "message": "您已经提交过作品，每个竞赛只能提交一个作品",
                "work_id": existing_work.id
            }
        )
    
    # 创建作品
    new_work = Work(
        title=work_data.title,
        description=work_data.description,
        file_url=work_data.file_url,
        thumbnail=work_data.thumbnail,
        user_id=current_user.id,
        contest_id=contest_id
    )
    
    db.add(new_work)
    
    # 更新参与者状态为已提交
    participant.status = "submitted"
    
    db.commit()
    db.refresh(new_work)
    
    # 获取用户信息
    user_info = {
        "id": current_user.id,
        "username": current_user.username,
        "nickname": current_user.nickname,
        "avatar": current_user.avatar
    }
    
    # 构建作品响应数据
    work_response = {
        "id": new_work.id,
        "title": new_work.title,
        "description": new_work.description,
        "file_url": new_work.file_url,
        "thumbnail": new_work.thumbnail,
        "views": new_work.views,
        "likes": new_work.likes,
        "comments": new_work.comments,
        "user_id": new_work.user_id,
        "contest_id": new_work.contest_id,
        "created_at": new_work.created_at.isoformat(),
        "updated_at": new_work.updated_at.isoformat() if new_work.updated_at else None,
        "user": user_info,
        "is_liked": False,
        "is_favorited": False
    }
    
    return ResponseModel(
        code=200,
        message="作品提交成功",
        data={
            "success": True,
            "message": "作品提交成功",
            "work_id": new_work.id,
            "work": work_response
        }
    )

@router.post("/{contest_id}/works/{work_id}/share", response_model=ResponseModel)
async def share_work(
    contest_id: int,
    work_id: int,
    share_data: WorkShareRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    转发竞赛作品
    
    Args:
        contest_id: 竞赛ID
        work_id: 作品ID
        share_data: 转发数据
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含转发结果的响应
    
    Raises:
        HTTPException: 如果作品不存在或不属于该竞赛
    """
    # 检查作品是否存在且属于该竞赛
    work = db.query(Work).filter(
        Work.id == work_id,
        Work.contest_id == contest_id
    ).first()
    
    if not work:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="作品不存在或不属于该竞赛"
        )
    
    # 检查用户是否已经在该平台转发过该作品
    existing_share = db.query(WorkShare).filter(
        WorkShare.user_id == current_user.id,
        WorkShare.work_id == work_id,
        WorkShare.platform == share_data.platform
    ).first()
    
    if existing_share:
        return ResponseModel(
            code=200,
            message="您已经在该平台转发过此作品",
            data={
                "success": True,
                "message": "您已经在该平台转发过此作品",
                "share_id": existing_share.id,
                "share_url": f"http://localhost:8000/share/{existing_share.id}"
            }
        )
    
    # 创建转发记录
    new_share = WorkShare(
        user_id=current_user.id,
        work_id=work_id,
        platform=share_data.platform,
        comment=share_data.comment
    )
    
    db.add(new_share)
    db.commit()
    db.refresh(new_share)
    
    # 生成分享链接
    share_url = f"http://localhost:8000/share/{new_share.id}"
    
    # 根据平台生成不同的分享消息
    platform_messages = {
        "wechat": "已生成微信分享链接",
        "weibo": "已生成微博分享链接",
        "qq": "已生成QQ分享链接",
        "link": "已生成通用分享链接"
    }
    
    message = platform_messages.get(share_data.platform, "作品转发成功")
    
    return ResponseModel(
        code=200,
        message=message,
        data={
            "success": True,
            "message": message,
            "share_id": new_share.id,
            "share_url": share_url
        }
    )

@router.get("/{contest_id}/status", response_model=ResponseModel)
async def get_contest_participation_status(
    contest_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户参与竞赛的状态
    
    Args:
        contest_id: 竞赛ID
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含参与状态的响应
    
    Raises:
        HTTPException: 如果竞赛不存在
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 检查竞赛是否存在
    contest = db.query(Contest).filter(Contest.id == contest_id).first()
    
    if not contest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="竞赛不存在"
        )
    
    # 查询用户参与记录
    participant = db.query(ContestParticipant).filter(
        ContestParticipant.user_id == current_user.id,
        ContestParticipant.contest_id == contest_id
    ).first()
    
    # 查询用户是否已提交作品
    submitted_work = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.contest_id == contest_id
    ).first()
    
    # 构建响应数据
    participation_data = {
        "contest_id": contest_id,
        "user_id": current_user.id,
        "is_participated": participant is not None,
        "participation_status": participant.status if participant else None,
        "participation_date": participant.created_at.isoformat() if participant else None,
        "has_submitted_work": submitted_work is not None,
        "submitted_work_id": submitted_work.id if submitted_work else None,
        "submitted_work_title": submitted_work.title if submitted_work else None,
        "submission_date": submitted_work.created_at.isoformat() if submitted_work else None,
        "contest_status": contest.status,
        "can_join": contest.status != ContestStatus.ENDED and participant is None,
        "can_submit": (
            contest.status == ContestStatus.ONGOING and 
            participant is not None and 
            submitted_work is None
        )
    }
    
    # 根据参与状态返回不同的消息
    if not participant:
        message = "您尚未参与该竞赛"
    elif submitted_work:
        message = "您已参与竞赛并提交了作品"
    else:
        message = "您已参与竞赛但尚未提交作品"
    
    return ResponseModel(
        code=200,
        message=message,
        data=participation_data
    )

@router.post("/{contest_id}/leave", response_model=ResponseModel)
async def leave_contest(
    contest_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    用户退出竞赛
    
    Args:
        contest_id: 竞赛ID
        current_user: 当前登录用户
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含退出结果的响应
    
    Raises:
        HTTPException: 如果竞赛不存在或用户未参与
    """
    # 更新竞赛状态
    update_contest_status(db)
    
    # 检查竞赛是否存在
    contest = db.query(Contest).filter(Contest.id == contest_id).first()
    
    if not contest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="竞赛不存在"
        )
    
    # 检查竞赛是否已结束
    if contest.status == ContestStatus.ENDED:
        return ResponseModel(
            code=400,
            message="竞赛已结束，无法退出",
            data={
                "success": False,
                "message": "竞赛已结束，无法退出",
                "contest_status": contest.status
            }
        )
    
    # 查询用户参与记录
    participant = db.query(ContestParticipant).filter(
        ContestParticipant.user_id == current_user.id,
        ContestParticipant.contest_id == contest_id
    ).first()
    
    if not participant:
        return ResponseModel(
            code=400,
            message="您尚未参与该竞赛，无法退出",
            data={
                "success": False,
                "message": "您尚未参与该竞赛，无法退出"
            }
        )
    
    # 检查用户是否已提交作品
    submitted_work = db.query(Work).filter(
        Work.user_id == current_user.id,
        Work.contest_id == contest_id
    ).first()
    
    if submitted_work:
        return ResponseModel(
            code=400,
            message="您已提交作品，无法退出竞赛",
            data={
                "success": False,
                "message": "您已提交作品，无法退出竞赛",
                "submitted_work_id": submitted_work.id,
                "submitted_work_title": submitted_work.title
            }
        )
    
    # 删除参与记录
    db.delete(participant)
    
    # 更新竞赛参与人数
    if contest.participant_count > 0:
        contest.participant_count -= 1
    
    # 删除相关的点赞、收藏、评论、转发记录（如果有的话）
    # 注意：这里只删除该用户对该竞赛作品的互动记录
    contest_works = db.query(Work).filter(Work.contest_id == contest_id).all()
    contest_work_ids = [work.id for work in contest_works]
    
    if contest_work_ids:
        # 删除该用户对该竞赛作品的点赞记录
        db.query(WorkLike).filter(
            WorkLike.user_id == current_user.id,
            WorkLike.work_id.in_(contest_work_ids)
        ).delete(synchronize_session=False)
        
        # 删除该用户对该竞赛作品的收藏记录
        db.query(WorkFavorite).filter(
            WorkFavorite.user_id == current_user.id,
            WorkFavorite.work_id.in_(contest_work_ids)
        ).delete(synchronize_session=False)
        
        # 删除该用户对该竞赛作品的评论记录
        db.query(WorkComment).filter(
            WorkComment.user_id == current_user.id,
            WorkComment.work_id.in_(contest_work_ids)
        ).delete(synchronize_session=False)
        
        # 删除该用户对该竞赛作品的转发记录
        db.query(WorkShare).filter(
            WorkShare.user_id == current_user.id,
            WorkShare.work_id.in_(contest_work_ids)
        ).delete(synchronize_session=False)
    
    db.commit()
    
    return ResponseModel(
        code=200,
        message="成功退出竞赛",
        data={
            "success": True,
            "message": "成功退出竞赛",
            "contest_id": contest_id,
            "user_id": current_user.id,
            "left_at": datetime.now().isoformat()
        }
    )